package com.dayuanit.dy15.ebook.bookshop.rpc;

import com.dayuanit.dy15.ebook.bookshop.domain.OrderDomain;
import com.dayuanit.dy15.ebook.bookshop.enums.OrderStatusEnum;
import com.dayuanit.dy15.ebook.bookshop.mapper.OrderMapper;
import com.dayuanit.dy15.ebook.bookshop.util.DateUtil;
import com.dayuanit.dy15.ebook.dto.OrderDTO;
import com.dayuanit.dy15.ebook.service.RpcOrderService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(version = "${demo.service.version}")
public class RpcOrderServiceImpl implements RpcOrderService {

    public RpcOrderServiceImpl() {
        System.out.println(">>>>>>>>>>>>>>>>>>>>RpcOrderServiceImpl");
    }

    @Autowired
    private OrderMapper orderMapper;

    @Value("${ebook.picture.url}")
    private String pictureUrl;

    @Override
    public List<OrderDTO> listUserOrder(long userId) {
        List<OrderDomain> orderDomains = orderMapper.listOrderInfos(userId);

        //k-订单ID  v-OrderDetailDTO
        Map<Long, List<OrderDTO.OrderDetailDTO>> orderDetailMap = orderDomains.stream()
                .flatMap(orderDomain -> orderDomain.getDetailDomains().stream())
                .map(domain -> {
                    OrderDTO.OrderDetailDTO orderDetailDTO = new OrderDTO.OrderDetailDTO();
                    orderDetailDTO.setBuyNum(domain.getBuyNum());
                    orderDetailDTO.setCommodityName(domain.getCommodityName());
                    orderDetailDTO.setPictureUrl(pictureUrl + domain.getPictureName());
                    orderDetailDTO.setOrderId(domain.getOrderId());
                    return orderDetailDTO;
                })
                .collect(Collectors.groupingBy(detailDomain -> detailDomain.getOrderId()));


        List<OrderDTO> dtos = new ArrayList<>(orderDomains.size());

        for (OrderDomain orderDomain : orderDomains) {
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setCreateTime(DateUtil.date2String(orderDomain.getCreateTime()));
            orderDTO.setOrderId(orderDomain.getOrderId());
            orderDTO.setOrderStatus(orderDomain.getOrderStatus());
            orderDTO.setRealName(orderDomain.getRealName());
            orderDTO.setStatusDesc(OrderStatusEnum.get(orderDomain.getOrderStatus()).getV());
            orderDTO.setTotalAmount(orderDomain.getTotalAmount());

            orderDTO.setOrderDetails(orderDetailMap.get(orderDomain.getOrderId()));
            dtos.add(orderDTO);
        }

        return dtos;
    }
}
